package com.onenine.app.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.Pair;
import android.view.View;

import com.alibaba.sdk.android.manager.OssManager;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.onenine.app.R;
import com.onenine.app.adapter.CoterieSelectAdapter;
import com.onenine.app.application.NineteenApp;
import com.onenine.app.db.DataManager;
import com.onenine.app.event.PostPublicEvent;
import com.onenine.app.event.RefreshEvent;
import com.onenine.app.model.CoterieItem;
import com.onenine.app.request.PostPublishRequest;
import com.onenine.app.utils.CDataProcessor;
import com.onenine.app.utils.DataType;
import com.onenine.app.utils.UrlConfig;
import com.onenine.app.view.dialog.PostPublishDialog;
import com.onenine.base.base.BasePageListActivity;
import com.onenine.base.okhttp.BaseResponse;
import com.onenine.base.okhttp.OkCallback;
import com.onenine.base.okhttp.OkRequest;
import com.onenine.base.utils.Toasty;
import com.onenine.base.view.PullRefreshRecyclerView;
import com.onenine.chat.rongcloud.RcUser;
import com.onenine.common.util.ApUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * 发贴选择圈子
 */
public class SelectCoterieActivity extends BasePageListActivity implements Runnable, OssManager.Callback {

    private PostPublicEvent mPostEvent;
    private CoterieItem mSelectCoterie;
    private boolean isUploading;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected Pair<PullRefreshRecyclerView, RecyclerView.Adapter> initPullRefreshView() {
        return Pair.create(findViewById(R.id.pull_to_refresh_layout), new CoterieSelectAdapter());
    }

    @Override
    protected void initViews() {
        super.initViews();
        mToolbar.setCenterTitle(R.string.select_coterie);
        mPullRefreshView.setRefreshBackgroundColor(Color.WHITE);
    }

    @Override
    protected void loadPageData(int pageNum) {
        List<CoterieItem> coterieList = DataManager.getAllCoteries();
        if (coterieList == null || coterieList.isEmpty()) {
            CDataProcessor.syncCoteries(this);
        } else {
            bindDataView(coterieList);
        }
    }

    private void bindDataView(List<CoterieItem> coterieList) {
        dismissRefreshStatus();
        notifyDataSuccess(coterieList);
    }

    @Override
    public void run() {
        bindDataView(DataManager.getAllCoteries());
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_pull_refresh_layout;
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(PostPublicEvent event) {
        this.mPostEvent = event;
        loadPageData(1);
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        mSelectCoterie = (CoterieItem) adapter.getItem(position);
        if (mPostEvent == null) {
            com.onenine.common.util.Logger.e("PostCoterieEvent为空");
            return;
        }
        if (isUploading) {
            Toasty.showNormal(R.string.submit_data_doing);
            return;
        }
        if (mSelectCoterie.getCoterieType() == DataType.COTERIE_IMAGE_VIDEO) {
            //图片视频圈子限定
            if (mPostEvent.pvList == null || mPostEvent.pvList.isEmpty()) {
                Toasty.showNormal(R.string.upload_video_image);
                return;
            }
        }
        if (mSelectCoterie.getCoterieType() == DataType.COTERIE_ASK) {
            //问答限定
            if (mPostEvent.pvType == DataType.POST_VIDEO_TYPE) {
                Toasty.showNormal(R.string.ask_invalid_hint);
                return;
            }
        }
        new PostPublishDialog(this, mSelectCoterie.getCoterieName(), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                confirmSubmitData();
            }
        }).show();
    }

    /**
     * 发布帖子
     */
    public void confirmSubmitData() {
        isUploading = true;
        if (mPostEvent.pvType == DataType.POST_IMAGE_TYPE) {
            if (mPostEvent.pvList == null || mPostEvent.pvList.isEmpty()) {
                //无图
                showLoading(R.string.submit_data_doing);
                submitData("");
            } else {
                //有图
                showLoading(R.string.upload_image_doing);
                OssManager.getInstance(ApUtils.getApp()).ossUpload(OssManager
                        .IMAGE_TYPE, mPostEvent.pvList, new ArrayList<>(), this);
            }
        } else {
            //视频
            showLoading(R.string.upload_video_doing);
            OssManager.getInstance(ApUtils.getApp()).ossUpload(OssManager
                    .VIDEO_TYPE, mPostEvent.pvList, new ArrayList<>(), this);
        }
    }

    /**
     * 提交数据
     *
     * @param mediaUrl
     */
    private void submitData(String mediaUrl) {
        PostPublishRequest request = new PostPublishRequest();
        request.setUserId(RcUser.getInstance().getUserId());
        request.setCoteriePkId(mSelectCoterie.getCoteriePkId());
        request.setPostDesc(mPostEvent.postDesc);
        request.setIsSyn(mPostEvent.isSync ? 1 : 0);
        request.setPvType(mPostEvent.pvType);
        request.setPostPvUrl(mediaUrl);
        OkRequest.getInstance().withUrl(mSelectCoterie.getCoterieType() == DataType.COTERIE_ASK
                ? UrlConfig.PUBLISH_ASK : UrlConfig.PUBLISH_POST)
                .withRequest(request).doRequest(SelectCoterieActivity.class.getSimpleName(), new OkCallback<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response, String srcData) {
                dismissLoading();
                isUploading = false;
                if (response.isSuccess()) {
                    Toasty.showNormal(R.string.publish_success);
                    EventBus.getDefault().post(new RefreshEvent(DataType.REFRESH_POST_PUBLISH_SUCCESS));
                    finish();
                } else {
                    Toasty.showNormal(response.getMessage());
                }
            }
        });
    }

    @Override
    public void onSuccess(String imageUrls) {
        submitData(imageUrls);
    }

    @Override
    public void onProgress(float progress) {

    }

    @Override
    public void onFailure(int errorCode, String errorMsg) {
        isUploading = false;
        NineteenApp.sHandler.post(new Runnable() {
            @Override
            public void run() {
                dismissLoading();
                Toasty.showNormal(errorMsg);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkRequest.getInstance().cancelTag(SelectCoterieActivity.class.getSimpleName());
        EventBus.getDefault().unregister(this);
        if (isUploading && mPostEvent != null && mPostEvent.pvList != null) {
            OssManager.getInstance(this)
                    .cancelAsyncTask(mPostEvent.pvList.toString());
        }
    }

}
